import { observer } from 'mobx-react-lite'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
  GestureResponderEvent,
  Image,
  LayoutChangeEvent,
  Pressable,
  SafeAreaView,
  StyleSheet,
  Text,
  View,
} from 'react-native'
import { useStore } from '../../store'
import Video, { OnProgressData, VideoRef } from 'react-native-video'
import { customPress } from '../../utils'
import { common } from '../../assets/style/common'
import VideoProgress, { VideoProgressDom } from './videoProgress'
import VideoMenu from './videoMenu'
import LikeIconWrap, { LikeIconWrapRef } from './likeIconWrap'
import Reanimated, {
  interpolate,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated'
import VideoFocus from './videoFocus'
import useGetStatusBar from '@/utils/useGetStatusBar'

interface VideoFullCardProp {
  videoMinHeight?: number // 最小视频的高度
  videoSource?: string
  videoId: string
}
export const VideoFullCard = observer((props: VideoFullCardProp) => {
  const videoMinHeight = (props.videoMinHeight || 380) - 58
  const [paddingTop] = useGetStatusBar()
  const videoRef = useRef<VideoRef>(null) // Video组件实例
  const videoProgressRef = useRef<VideoProgressDom>(null) // 进度条组件实例
  const likeIconWrapRef = useRef<LikeIconWrapRef>(null)
  const { variableStore, videoSwiperStore } = useStore()
  const screenWidth = variableStore.screen.width
  const [progress, setProgress] = useState<OnProgressData>({
    seekableDuration: 1, // 总时间
    playableDuration: 1, // 已下载的可播放的进度
    currentTime: 0, // 当前播放进度
  })
  const videoInfo = useMemo(() => {
    return videoSwiperStore.getVideoById(props.videoId)
  }, [props.videoId])
  const [videoHeight, setVideoHeight] = useState(0)
  const smallVideo = useShowComment()
  const videoWrapStyle = useAnimatedStyle(() => {
    if (!videoHeight) {
      return {
        opacity: 0,
      }
    }
    return {
      height: withTiming(
        interpolate(smallVideo.value, [0, 1], [videoHeight, videoMinHeight]),
        {
          duration: 300,
        },
      ),
      opacity: 1,
    }
  }, [videoHeight, videoMinHeight])
  const [paused, setPaused] = useState(true)
  // 如果当前的swiperId改变了
  function onProgress(e: OnProgressData) {
    setProgress(e)
    videoProgressRef.current?.changeCrnPrgWdt(
      (e.currentTime / e.seekableDuration) * screenWidth,
      'crn',
    )
    videoProgressRef.current?.changeCrnPrgWdt(
      (e.playableDuration / e.seekableDuration) * screenWidth,
      'ply',
    )
  }
  // 视频播放结束
  function onVideoEnd() {
    setPaused(true)
    setProgress(val => {
      if (val.currentTime !== val.seekableDuration) {
        videoProgressRef.current?.changeCrnPrgWdt(screenWidth, 'crn')
        return Object.assign({}, val, { currentTime: val.seekableDuration })
      }
      return val
    })
  }
  const onVideoPress = useCallback(
    customPress((type: 'doubleClick' | 'click', e: GestureResponderEvent) => {
      e.persist()
      if (!e.nativeEvent) return
      const { pageX, pageY } = e.nativeEvent
      switch (type) {
        case 'click': {
          //单点设置暂停
          if (videoSwiperStore.showCommentPage) {
            videoSwiperStore.setShowCommentPage(false)
            break
          }
          setPaused(true)
          break
        }
        case 'doubleClick': {
          //双击设置是否喜欢
          if (!videoInfo?.meLike) {
            videoSwiperStore.setVideoLike(props.videoId)
          }
          const rotateZ = Math.random() * 20
          likeIconWrapRef.current?.pushList({
            translateX: pageX,
            translateY: pageY,
            id: Date.now(),
            rotateZ: Math.random() <= 0.5 ? rotateZ * -1 : rotateZ,
          })
          break
        }
      }
    }),
    [],
  )
  function onVideoLayout(e: LayoutChangeEvent) {
    setVideoHeight(e.nativeEvent.layout.height)
  }
  // 点击状态条
  function onPressProgress(e: GestureResponderEvent) {
    const { pageX } = e.nativeEvent
    const current =
      progress.seekableDuration * (pageX / variableStore.screen.width) // 获取播放的时间
    videoRef.current?.seek(current)
    setPaused(false)
  }
  function onStartVideo(e: GestureResponderEvent) {
    e.stopPropagation()
    if (progress.currentTime === progress.seekableDuration) {
      videoRef.current?.seek(0)
    }
    setPaused(false)
  }

  useEffect(() => {
    if (videoSwiperStore.currentVideoId === props.videoId) {
      // 第一次默认播放
      if (videoInfo?.isFirstShow) {
        setPaused(false)
        videoSwiperStore.setVideoUnFirst(props.videoId)
      }
    } else {
      setPaused(true)
    }
  }, [videoSwiperStore.currentVideoId])
  return (
    <View style={style.cardContain}>
      <View style={[style.videoBox, { paddingTop }]}>
        <View style={style.videoDomWrap} onLayout={onVideoLayout}>
          <Reanimated.View style={[style.videoAnimatedStyle, videoWrapStyle]}>
            <Pressable
              style={[style.videoDom, style.videoPressWrap]}
              onPress={onVideoPress}
            >
              <View
                style={[
                  style.videoPlusIcon,
                  common.flexCol,
                  {
                    opacity: paused ? 1 : 0,
                    marginLeft: paused ? 'auto' : '100%',
                  },
                ]}
              >
                <Pressable onPress={onStartVideo}>
                  <Text style={style.plusIcon}>&#xe625;</Text>
                </Pressable>
              </View>
              <LikeIconWrap ref={likeIconWrapRef} />
            </Pressable>
            <View style={style.videoDom}>
              <Video
                ref={videoRef}
                style={{ width: '100%', height: '100%' }}
                source={{
                  uri: props.videoSource,
                }}
                onProgress={onProgress}
                onEnd={onVideoEnd}
                paused={paused}
              />
            </View>
          </Reanimated.View>
        </View>
        <SafeAreaView style={{ position: 'relative' }}>
          <View style={style.btnWrap} />
        </SafeAreaView>
      </View>
      <View style={style.cardFootWrap}>
        <View style={style.cardFootPadding}>
          <View style={[common.flexCol, style.userInfoWrap]}>
            <Image
              style={style.uploadUser}
              resizeMode="cover"
              source={videoInfo?.authorCover}
            />
            <Text style={style.userName}>{videoInfo?.author}</Text>
            <VideoFocus />
            <Pressable style={[style.trumptBtn, common.flexCol]}>
              <Text style={style.trumptIcon}>&#xe8b8;</Text>
            </Pressable>
          </View>
          <View style={style.contexture}>
            <Text style={style.cntLabel} numberOfLines={2}>
              {videoInfo?.description}
            </Text>
          </View>
          <VideoProgress
            ref={videoProgressRef}
            onPressProgress={onPressProgress}
          />
          <VideoMenu showCommetIcon={true} videoInfo={videoInfo} />
        </View>
      </View>
    </View>
  )
})
export function useShowComment() {
  const { videoSwiperStore } = useStore()
  const showComment = useSharedValue(videoSwiperStore.showCommentPage ? 1 : 0)
  useEffect(() => {
    showComment.value = videoSwiperStore.showCommentPage ? 1 : 0
  }, [videoSwiperStore.showCommentPage])

  return showComment
}
const style = StyleSheet.create({
  backIcon: {
    fontFamily: 'iconfont',
    fontSize: 24,
    color: '#fff',
  },
  videoSwiper: {
    position: 'relative',
    width: '100%',
    height: '100%',
  },

  headerMenu: {
    position: 'absolute',
    zIndex: 10,
    paddingHorizontal: 12,
  },
  videoWrap: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    left: 0,
    top: 0,
  },
  videoBox: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    left: 0,
    top: 0,
    display: 'flex',
    flexDirection: 'column',
    backgroundColor: 'transparent',
    paddingBottom: 40,
  },
  cardContain: {
    width: '100%',
    height: '100%',
  },
  videoDomWrap: {
    width: '100%',
    flex: 1,
    position: 'relative',
  },
  videoLikeWrap: {
    position: 'absolute',
    left: -40,
    top: -40,
    width: 80,
    height: 80,
    backgroundColor: '#ffffff66',
    borderRadius: 20,
  },
  videoLike: {
    fontFamily: 'iconfont',
    color: '#f392a6',
    fontSize: 80,
  },
  videoPressWrap: {
    zIndex: 2,
    position: 'absolute',
  },
  videoPlusIcon: {
    width: 80,
    height: 80,
    left: '50%',
    top: '50%',
    transform: [{ translateY: -40 }, { translateX: -40 }],
    position: 'absolute',
    borderRadius: 40,
    justifyContent: 'center',
  },
  plusIcon: {
    fontFamily: 'iconfont',
    fontSize: 64,
    color: '#ddd',
  },
  videoDom: {
    position: 'relative',
    left: 0,
    top: 0,
    width: '100%',
    height: '100%',
    paddingBottom: 12,
  },
  videoAnimatedStyle: {
    width: '100%',
    position: 'relative',
  },
  userInfoWrap: {
    marginBottom: 8,
    paddingHorizontal: 12,
  },
  cardFootWrap: {
    position: 'absolute',
    width: '100%',
    bottom: 0,
    left: 0,
    zIndex: 10,
    paddingBottom: 20,
  },
  cardFootPadding: {
    width: '100%',
  },
  cntLabel: {
    fontSize: 14,
    color: '#fff',
    lineHeight: 18,
  },
  uploadUser: {
    width: 34,
    height: 34,
    borderRadius: 17,
  },
  userName: {
    color: '#fff',
    fontSize: 18,
    paddingHorizontal: 8,
    fontWeight: 'bold',
  },

  contexture: {
    height: 44,
    marginBottom: 10,
    paddingHorizontal: 12,
  },

  pencilIcon: {
    fontFamily: 'iconfont',
    color: '#999',
    paddingRight: 4,
    fontSize: 18,
  },
  pencilTxt: {
    fontSize: 14,
    color: '#999',
  },
  trumptBtn: {
    backgroundColor: '#11111188',
    marginLeft: 'auto',
    width: 24,
    height: 24,
    borderRadius: 12,
    justifyContent: 'center',
  },
  trumptIcon: {
    fontFamily: 'iconfont',
    fontSize: 16,
    color: '#fff',
  },
  footBtn: {
    display: 'flex',
    justifyContent: 'center',
    marginLeft: 24,
  },
  inputBtn: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: 20,
    paddingVertical: 6,
    backgroundColor: '#444',
    borderRadius: 16,
  },
  footIcon: {
    fontSize: 26,
    color: '#fff',
    fontFamily: 'iconfont',
    paddingBottom: 2,
  },
  footBtnCount: {
    fontSize: 16,
    textAlign: 'center',
    color: '#fff',
  },
  progressWrap: {
    height: 8,
    width: '100%',
    zIndex: 10,
    position: 'relative',
  },
  progress: {
    position: 'absolute',
    bottom: 3,
    height: 2,
    width: '100%',
    left: '-100%',
  },
  progressCurrent: {
    backgroundColor: '#666',
    zIndex: 2,
  },
  progressPlayable: {
    backgroundColor: '#313131',
  },
  btnWrap: {
    width: '100%',
    height: 60,
    paddingHorizontal: 12,
  },
  fullBtn: {
    position: 'absolute',
    width: 90,
    height: 32,
    justifyContent: 'center',
    borderRadius: 2,
    borderWidth: 1,
    borderColor: '#555',
    bottom: '30%',
    left: '50%',
    zIndex: 10,
    backgroundColor: '#33333388',
    transform: [{ translateX: -45 }],
  },
  fullIcon: {
    fontFamily: 'iconfont',
    color: '#fff',
    fontSize: 16,
  },
  fullTxt: {
    color: '#fff',
    fontSize: 14,
    textAlign: 'center',
  },
})
